<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
    <style type="text/css"></style>
  </head>

  <body>
    <script type="text/javascript">
      var data = [
        { name: "根目录1", id: 1, parentId: 0 },
        { name: "根目录2", id: 2, parentId: 0 },
        { name: "子目录1-1", id: 3, parentId: 1 },
        { name: "子目录1-2", id: 4, parentId: 1 },
        { name: "子目录2-1", id: 5, parentId: 2 },
        { name: "孙目录1-2-1", id: 6, parentId: 4 },
      ];

      function Tree(data, id) {
        let arr = [];

        data.forEach((item, index) => {
          if (item.parentId == id) {
            let len = Tree(data, item.id);
            if (len.length > 0) {
              item.children = len;
            }
            arr.push(item);
          }
        });
        return arr;
      }
      console.log(53, Tree(data, 0));
    </script>
  </body>
</html>
